// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/dwio/dwrf/reader/selective_struct_column_reader.h>
#include "melon/conv.h"
#include <pollux/dwio/common/column_loader.h>
#include <pollux/dwio/dwrf/reader/selective_dwrf_reader.h>

namespace kumo::pollux::dwrf {

using namespace dwio::common;

SelectiveStructColumnReader::SelectiveStructColumnReader(
    const TypePtr& requestedType,
    const std::shared_ptr<const TypeWithId>& fileType,
    DwrfParams& params,
    common::ScanSpec& scanSpec,
    bool isRoot)
    : SelectiveStructColumnReaderBase(
          requestedType,
          fileType,
          params,
          scanSpec,
          isRoot) {
  EncodingKey encodingKey{fileType_->id(), params.flatMapContext().sequence};
  auto& stripe = params.stripeStreams();

  // A reader tree may be constructed while the ScanSpec is being used
  // for another read. This happens when the next stripe is being
  // prepared while the previous one is reading.
  if (stripe.format() == DwrfFormat::kDwrf) {
    auto encoding =
        static_cast<int64_t>(stripe.getEncoding(encodingKey).kind());

    DWIO_ENSURE_EQ(
        encoding,
        proto::ColumnEncoding_Kind_DIRECT,
        "Unknown encoding for StructColumnReader");
  } else {
    auto encoding =
        static_cast<int64_t>(stripe.getEncodingOrc(encodingKey).kind());

    DWIO_ENSURE_EQ(
        encoding,
        proto::orc::ColumnEncoding_Kind_DIRECT,
        "Unknown encoding for StructColumnReader");
  }

  // A reader tree may be constructed while the ScanSpec is being used
  // for another read. This happens when the next stripe is being
  // prepared while the previous one is reading.
  auto& childSpecs = scanSpec.stableChildren();
  const auto& rowType = requestedType_->as_row();
  for (auto i = 0; i < childSpecs.size(); ++i) {
    auto* childSpec = childSpecs[i];
    if (childSpec->isConstant() || isChildMissing(*childSpec)) {
      childSpec->setSubscript(kConstantChildSpecSubscript);
      continue;
    }
    if (!childSpec->readFromFile()) {
      continue;
    }

    const auto childFileType = fileType_->childByName(childSpec->fieldName());
    const auto childRequestedType = rowType.findChild(childSpec->fieldName());
    auto labels = params.streamLabels().append(melon::to<std::string>(i));
    auto childParams = DwrfParams(
        stripe,
        labels,
        params.runtimeStatistics(),
        FlatMapContext{
            .sequence = encodingKey.sequence(),
            .inMapDecoder = nullptr,
            .keySelectionCallback = nullptr});
    addChild(SelectiveDwrfReader::build(
        childRequestedType, childFileType, childParams, *childSpec));
    childSpec->setSubscript(children_.size() - 1);
  }
}

void SelectiveStructColumnReaderBase::seekTo(
    int64_t offset,
    bool readsNullsOnly) {
  if (offset == readOffset_) {
    return;
  }
  if (readOffset_ < offset) {
    if (numParentNulls_) {
      POLLUX_CHECK_LE(
          parentNullsRecordedTo_,
          offset,
          "Must not seek to before parentNullsRecordedTo_");
    }
    auto distance = offset - readOffset_ - numParentNulls_;
    auto numNonNulls = formatData_->skipNulls(distance);
    // We inform children how many nulls there were between original position
    // and destination. The children will seek this many less. The
    // nulls include the nulls found here as well as the enclosing
    // level nulls reported to this by parents.
    for (auto& child : children_) {
      if (child) {
        child->addSkippedParentNulls(
            readOffset_, offset, numParentNulls_ + distance - numNonNulls);
      }
    }
    numParentNulls_ = 0;
    parentNullsRecordedTo_ = 0;
    readOffset_ = offset;
  } else {
    POLLUX_FAIL("Seeking backward on a ColumnReader");
  }
}

} // namespace kumo::pollux::dwrf
